package com.rolerealm.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rolerealm.common.exception.BusinessException;
import com.rolerealm.common.constant.ErrorCode;
import com.rolerealm.dao.UserInteractionMapper;
import com.rolerealm.domain.entity.UserInteractionEntity;
import com.rolerealm.domain.vo.PageResult;
import com.rolerealm.domain.vo.UserFavoriteVO;
import com.rolerealm.domain.vo.CharacterDetailVO;
import com.rolerealm.service.UserFavoriteService;
import com.rolerealm.service.CharacterService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserFavoriteServiceImpl implements UserFavoriteService {

    private final UserInteractionMapper userInteractionMapper;
    private final CharacterService characterService;

    @Override
    public void addFavorite(Long userId, Long characterId) {
        if (characterId == null) {
            throw new BusinessException(ErrorCode.PARAM_MISSING);
        }
        
        // 检查是否已经收藏
        int exists = userInteractionMapper.existsByUserAndCharacterAndType(userId, characterId, "favorite");
        if (exists > 0) {
            return;
        }
        
        // 创建收藏记录
        UserInteractionEntity entity = UserInteractionEntity.builder()
                .userId(userId)
                .characterId(characterId)
                .interactionType("favorite")
                .durationSeconds(0)
                .build();
        int inserted = userInteractionMapper.insert(entity);
        if (inserted != 1) {
            throw new BusinessException(ErrorCode.USER_FAVORITE_ADD_FAILED);
        }
    }

    @Override
    public void removeFavorite(Long userId, Long characterId) {
        if (characterId == null) {
            throw new BusinessException(ErrorCode.PARAM_MISSING);
        }
        
        int affected = userInteractionMapper.delete(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserInteractionEntity>()
                        .eq(UserInteractionEntity::getUserId, userId)
                        .eq(UserInteractionEntity::getCharacterId, characterId)
                        .eq(UserInteractionEntity::getInteractionType, "favorite"));
        if (affected < 0) {
            throw new BusinessException(ErrorCode.USER_FAVORITE_REMOVE_FAILED);
        }
    }

    @Override
    public PageResult<UserFavoriteVO> pageFavorites(Long userId, Integer page, Integer size) {
        // 查询收藏记录
        Page<UserInteractionEntity> mpPage = new Page<>(page, size);
        Page<UserInteractionEntity> res = userInteractionMapper.selectPage(mpPage,
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserInteractionEntity>()
                        .eq(UserInteractionEntity::getUserId, userId)
                        .eq(UserInteractionEntity::getInteractionType, "favorite")
                        .orderByDesc(UserInteractionEntity::getCreatedAt));
        
        // 获取角色ID列表
        List<Long> characterIds = res.getRecords().stream()
                .map(UserInteractionEntity::getCharacterId)
                .collect(Collectors.toList());
        
        // 查询角色详情
        List<UserFavoriteVO> list = new ArrayList<>();
        if (!characterIds.isEmpty()) {
            // 批量查询角色详情
            Map<Long, CharacterDetailVO> characterMap = new HashMap<>();
            for (Long characterId : characterIds) {
                try {
                    CharacterDetailVO character = characterService.getCharacterDetail(characterId);
                    characterMap.put(characterId, character);
                } catch (Exception e) {
                    // 如果角色不存在或查询失败，跳过
                    continue;
                }
            }
            
            // 构建收藏列表
            list = res.getRecords().stream().map(e -> {
                UserFavoriteVO vo = new UserFavoriteVO();
                vo.setCharacterId(e.getCharacterId());
                vo.setFavoritedAt(e.getCreatedAt() == null ? null : e.getCreatedAt().toInstant(ZoneOffset.UTC).toEpochMilli());
                
                // 填充角色详情
                CharacterDetailVO character = characterMap.get(e.getCharacterId());
                if (character != null) {
                    vo.setCharacterName(character.getName());
                    vo.setAvatarUrl(character.getAvatarUrl());
                    vo.setDescription(character.getDescription());
                    vo.setCategory(character.getCategory());
                    vo.setSkillType(character.getSkillType());
                }
                
                return vo;
            }).collect(Collectors.toList());
        }
        
        return PageResult.of(list, page, size, res.getTotal());
    }
}


